const {result,parseArrayString} = require("common-utils");
const uniID=require("uni-id-common");
const db = uniCloud.database();
const dbCmd = db.command;

const extStorageManager = uniCloud.getExtStorageManager({
	provider: "qiniu",
	domain: "xxmcdn.qingnian8.com", // 域名地址
});
module.exports = {
	_before:async function () { // 通用预处理器		
		this.httpInfo = this.getHttpInfo();		
		let {httpMethod="GET",headers:{token},queryStringParameters=null,body=null} = this.httpInfo
		this.httpMethod = httpMethod.toUpperCase();
		this.queryStringParameters = queryStringParameters;
		this.body = body ? JSON.parse(body) : null;
		
		if(!token) throw result({code:401,msg:"required",custom:"必须传递token"});
		const clientInfo = this.getClientInfo()
		const uniIDIns = uniID.createInstance({
			clientInfo
		})	
		let {errCode,uid,exp} =  await uniIDIns.checkToken(token);
		this.uid = uid;
		if(errCode == 'uni-id-check-token-failed') throw result({code:403,msg:"error",custom:"token校验未通过"});
		if(errCode == 'uni-id-token-expired') throw result({code:401,msg:"error",custom:"token已失效"});	
	},
	async getUploadFileOptions(data){
		try{
			if(this.httpMethod!="GET") return result({code:400,msg:"error",custom:"method类型需要GET"});
			let {
				cloudPath, // 前端传过来的文件路径
			} = data;					
			// 最后调用 extStorageManager.getUploadFileOptions
			let uploadFileOptionsRes = await extStorageManager.getUploadFileOptions({
				cloudPath: cloudPath,
				allowUpdate: false, // 是否允许覆盖更新，如果返回前端，建议设置false，代表仅新增，不可覆盖
				fsizeLimit:10485760
			});
			return result({code:200,msg:"success",data:uploadFileOptionsRes}); 
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	async deleteFile(){
		if(this.httpMethod!="DELETE") return result({code:400,msg:"error",custom:"method类型需要DELETE"});
		let {files} = this.body;
		if(!(files && Array.isArray(files) && files.length)) return result({code:400,msg:"error",custom:"files需要Array类型并且不能为空"});	
		let res =await extStorageManager.deleteFile({
			fileList:files// 待删除的文件地址列表
		});		
		return result({code:200,msg:"success",data:res.fileList}); 
	}
}
